//
//  RadioPageController.m
//  PetTown
//
//  Created by lanou3g on 15/5/28.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "RadioPageController.h"
#import "RadioPageCell.h"
#import "JSONKit.h"
#import "RadioPage.h"
#import "UIImageView+WebCache.h"
#import "RadioDetailsTableViewController.h"
#import "RadioPlayViewController.h"
#import "MBProgressHUD.h"
#import "UIScrollView+MJRefresh.h"
@interface RadioPageController ()
{
    MBProgressHUD * mbBar;
}
@end

@implementation RadioPageController

- (void)viewDidLoad {
    [super viewDidLoad];
    //下拉刷新
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];

    [self readData];//读取数据
    [self setBarButtonItem];//设置BarButtonItem
    //初始化数组
    self.hotlistArray = [NSMutableArray array];
    self.carouselArray = [NSMutableArray array];
    self.alllistArray = [NSMutableArray array];
    self.radioUrlArray = [NSMutableArray array];
    self.titleArray  = [NSMutableArray array];
    self.radioImgUrlArray = [NSMutableArray array];
    
    
    
//
    
}

//下拉刷新

- (void)headerRereshing{
    
    [self.tableView headerEndRefreshing];
}

//设置BarButtonItem
-(void)setBarButtonItem{
    UIButton * retunButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    retunButton.frame = CGRectMake(0, 0, 32, 32);
    [retunButton setBackgroundImage:[UIImage imageNamed:nil] forState:UIControlStateNormal];
    [retunButton addTarget:self action:nil forControlEvents:UIControlEventTouchDown];
    UIBarButtonItem * leftBI = [[UIBarButtonItem alloc] initWithCustomView:retunButton];
    self.navigationItem.leftBarButtonItem = leftBI;
    self.navigationItem.title = @"片刻";
}

//请求数据
-(void)readData{
    mbBar = [[MBProgressHUD alloc] initWithView:self.tableView];
    [self.tableView addSubview:mbBar];
    mbBar.labelText = @"正在加载..";
    [mbBar show:YES];
    
    NSURL * URL = [NSURL URLWithString:RadioPageAPI];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
    [request setHTTPMethod:@"POSY"];//设置请求方式
    NSData * data = [RadioPageSplicing dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];

    //通过block方式请求
    NSOperationQueue * mainQueue = [NSOperationQueue mainQueue];
    __weak RadioPageController * radioPageTVC = self;
    [NSURLConnection sendAsynchronousRequest:request queue:mainQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (nil == data) {
            return ;
        }
        NSMutableDictionary * dic = [data objectFromJSONData];
        NSMutableDictionary * diction = [dic objectForKey:@"data"];
        NSArray * array = [diction objectForKey:@"alllist"];
        radioPageTVC.carouselArray = [diction objectForKey:@"carousel"];
        radioPageTVC.hotlistArray = [diction objectForKey:@"hotlist"];
        for (NSMutableDictionary * dict in array) {
            RadioPage * radioPage = [[RadioPage alloc] init];
            [radioPage setValuesForKeysWithDictionary:dict];
            [radioPageTVC.alllistArray addObject:radioPage];
        }
        [self.tableView reloadData];
        [self setHeaderField];//设置表头

    }];
    
}
//设置表头
- (void)setHeaderField
{
    //设置表头
    self.showTitleImageView = [[ShowTitleImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetWidth(self.view.frame)/3 * 2 + 20)];
    _showTitleImageView.carouselArray = _carouselArray;
    _showTitleImageView.hotlistArray = _hotlistArray;
    self.tableView.tableHeaderView = _showTitleImageView;

   //设置代理
    _showTitleImageView.scrollView.delegate = self;

    //button事件
    [_showTitleImageView.leftButton addTarget:self action:@selector(leftButtonClick:) forControlEvents:UIControlEventTouchDown];
    [_showTitleImageView.centerButton addTarget:self action:@selector(centerButtonClick:) forControlEvents:UIControlEventTouchDown];
    [_showTitleImageView.rightButton addTarget:self action:@selector(rightButtonClick:) forControlEvents:UIControlEventTouchDown];
    
    
}





//button点击事件
- (void)leftButtonClick:(UIButton *)button{
    NSDictionary * leftdic = _hotlistArray[0];
    RadioDetailsTableViewController * radioDTVC = [[RadioDetailsTableViewController alloc] init];
    radioDTVC.radioid = [leftdic objectForKey:@"radioid"];
    [self.navigationController pushViewController:radioDTVC animated:YES];

}
//button点击事件
- (void)centerButtonClick:(UIButton *)button{
    NSDictionary * centerdic = _hotlistArray[1];
    RadioDetailsTableViewController * radioDTVC = [[RadioDetailsTableViewController alloc] init];
    radioDTVC.radioid = [centerdic objectForKey:@"radioid"];
    [self.navigationController pushViewController:radioDTVC animated:YES];
}
//button点击事件
- (void)rightButtonClick:(UIButton *)button{
    NSDictionary * rightdic = _hotlistArray[2];
    RadioDetailsTableViewController * radioDTVC = [[RadioDetailsTableViewController alloc] init];
    radioDTVC.radioid = [rightdic objectForKey:@"radioid"];
    [self.navigationController pushViewController:radioDTVC animated:YES];
}

//实现协议中得方法 滑动结束触发
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //滑动结束改变pageControl的圆点位置
    _showTitleImageView.pageControl.currentPage = scrollView.contentOffset.x/CGRectGetWidth(scrollView.frame);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    //清除缓存
    SDImageCache * sdI = [SDImageCache sharedImageCache];
    [sdI clearDisk];
    [sdI clearMemory];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return _alllistArray.count;
}

//设置cell 内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RadioPageCell *cell =[tableView dequeueReusableCellWithIdentifier:@"radiomyCell" ];
    if (!cell) {
        cell=[[RadioPageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"radiomyCell"];
        
    }
    
    RadioPage * radioPage = _alllistArray[indexPath.row];
    cell.radioPage = radioPage;
    NSURL * url = [NSURL URLWithString:[radioPage coverimg]];
    [cell.leftImg sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"place.jpg"]];
    
    [MBProgressHUD hideHUDForView:self.tableView animated:YES];

    
    return cell;
}
//点击cell推出
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RadioDetailsTableViewController * radioDTVC = [[RadioDetailsTableViewController alloc] init];
    radioDTVC.radioid = [_alllistArray[indexPath.row] radioid];
    radioDTVC.radioTitle = [_alllistArray[indexPath.row] title];
    [self.navigationController pushViewController:radioDTVC animated:YES];
    
}
//设置cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
//设置区头标题
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSString * str = @"全部电台";
    
    return str;
}
//设置区头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here, for example:
    // Create the next view controller.
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
    
    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
